#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
用户视频管理服务 - 提供视频上传、审核、管理和排序功能
"""

from typing import Dict, List, Optional, Any
import os
import uuid
from datetime import datetime
from flask import current_app
from sqlalchemy import and_, or_
from app import db
from app.models.user import User
from app.models.user_video import UserVideo
from app.models.file_upload import FileUpload


class UserVideoService:
    """用户视频管理服务类"""
    
    # 视频状态常量
    STATUS_PENDING = 1      # 待审核
    STATUS_APPROVED = 2     # 审核通过
    STATUS_REJECTED = 3     # 审核拒绝
    
    # 最大视频数量限制
    MAX_VIDEOS_PER_USER = 6
    
    # 视频文件限制
    MAX_FILE_SIZE = 50 * 1024 * 1024  # 50MB
    ALLOWED_EXTENSIONS = ['mp4', 'mov', 'avi', 'wmv', 'flv']
    MAX_DURATION = 60  # 最大60秒
    
    @classmethod
    def get_user_videos(cls, user_id: int, include_pending: bool = True) -> List[Dict[str, Any]]:
        """
        获取用户视频列表
        
        Args:
            user_id: 用户ID
            include_pending: 是否包含待审核视频
            
        Returns:
            视频列表
        """
        try:
            query = UserVideo.query.filter_by(user_id=user_id)
            
            if not include_pending:
                query = query.filter(UserVideo.status == cls.STATUS_APPROVED)
            
            videos = query.order_by(UserVideo.sort_order.asc(), UserVideo.created_at.desc()).all()
            
            return [video.to_dict() for video in videos]
            
        except Exception as e:
            current_app.logger.error(f"获取用户视频异常: {str(e)}")
            return []
    
    @classmethod
    def upload_video(cls, user_id: int, file_data: Dict[str, Any]) -> Dict[str, Any]:
        """
        上传用户视频
        
        Args:
            user_id: 用户ID
            file_data: 文件数据
            
        Returns:
            上传结果
        """
        try:
            # 检查用户是否存在
            user = User.query.get(user_id)
            if not user:
                return {'success': False, 'error': '用户不存在'}
            
            # 检查视频数量限制
            current_count = UserVideo.query.filter_by(user_id=user_id).count()
            if current_count >= cls.MAX_VIDEOS_PER_USER:
                return {'success': False, 'error': f'视频数量已达上限({cls.MAX_VIDEOS_PER_USER}个)'}
            
            # 验证文件信息
            validation_result = cls._validate_video_file(file_data)
            if not validation_result['is_valid']:
                return {'success': False, 'error': validation_result['error']}
            
            # 创建文件上传记录
            file_upload = FileUpload(
                user_id=user_id,
                original_name=file_data.get('original_name'),
                saved_name=file_data.get('saved_name'),
                file_path=file_data.get('file_path'),
                file_size=file_data.get('file_size'),
                file_type='video',
                status=1
            )
            db.session.add(file_upload)
            db.session.flush()  # 获取file_upload.id
            
            # 创建用户视频记录
            video = UserVideo(
                user_id=user_id,
                video_file_id=file_upload.id,
                video_url=file_data.get('video_url'),
                thumbnail_url=file_data.get('thumbnail_url'),
                duration=file_data.get('duration', 0),
                sort_order=current_count + 1,
                status=cls.STATUS_PENDING
            )
            db.session.add(video)
            db.session.commit()
            
            return {
                'success': True,
                'data': video.to_dict(),
                'message': '视频上传成功，等待审核'
            }
            
        except Exception as e:
            db.session.rollback()
            current_app.logger.error(f"上传视频异常: {str(e)}")
            return {'success': False, 'error': f'上传失败: {str(e)}'}
    
    @classmethod
    def delete_video(cls, user_id: int, video_id: int) -> Dict[str, Any]:
        """
        删除用户视频
        
        Args:
            user_id: 用户ID
            video_id: 视频ID
            
        Returns:
            删除结果
        """
        try:
            video = UserVideo.query.filter_by(id=video_id, user_id=user_id).first()
            if not video:
                return {'success': False, 'error': '视频不存在'}
            
            # 删除文件记录和物理文件
            if video.video_file:
                # 这里可以添加物理文件删除逻辑
                # os.remove(video.video_file.file_path)
                db.session.delete(video.video_file)
            
            # 删除视频记录
            db.session.delete(video)
            
            # 重新排序剩余视频
            remaining_videos = UserVideo.query.filter(
                and_(
                    UserVideo.user_id == user_id,
                    UserVideo.sort_order > video.sort_order
                )
            ).all()
            
            for remaining_video in remaining_videos:
                remaining_video.sort_order -= 1
            
            db.session.commit()
            
            return {'success': True, 'message': '视频删除成功'}
            
        except Exception as e:
            db.session.rollback()
            current_app.logger.error(f"删除视频异常: {str(e)}")
            return {'success': False, 'error': f'删除失败: {str(e)}'}
    
    @classmethod
    def reorder_videos(cls, user_id: int, video_orders: List[Dict[str, int]]) -> Dict[str, Any]:
        """
        重新排序用户视频
        
        Args:
            user_id: 用户ID
            video_orders: 视频排序列表 [{'video_id': 1, 'sort_order': 1}, ...]
            
        Returns:
            排序结果
        """
        try:
            # 验证所有视频是否属于当前用户
            video_ids = [item['video_id'] for item in video_orders]
            user_videos = UserVideo.query.filter(
                and_(
                    UserVideo.user_id == user_id,
                    UserVideo.id.in_(video_ids)
                )
            ).all()
            
            if len(user_videos) != len(video_ids):
                return {'success': False, 'error': '部分视频不存在或不属于当前用户'}
            
            # 更新排序
            for order_item in video_orders:
                video = next((v for v in user_videos if v.id == order_item['video_id']), None)
                if video:
                    video.sort_order = order_item['sort_order']
            
            db.session.commit()
            
            # 返回更新后的视频列表
            updated_videos = cls.get_user_videos(user_id)
            
            return {
                'success': True,
                'data': updated_videos,
                'message': '视频排序成功'
            }
            
        except Exception as e:
            db.session.rollback()
            current_app.logger.error(f"重排序视频异常: {str(e)}")
            return {'success': False, 'error': f'排序失败: {str(e)}'}
    
    @classmethod
    def get_video_detail(cls, video_id: int, user_id: Optional[int] = None) -> Optional[Dict[str, Any]]:
        """
        获取视频详情
        
        Args:
            video_id: 视频ID
            user_id: 用户ID（用于权限检查）
            
        Returns:
            视频详情
        """
        try:
            query = UserVideo.query.filter_by(id=video_id)
            
            if user_id:
                query = query.filter_by(user_id=user_id)
            
            video = query.first()
            if not video:
                return None
            
            video_data = video.to_dict()
            
            # 添加文件信息
            if video.video_file:
                video_data['file_info'] = {
                    'original_name': video.video_file.original_name,
                    'file_size': video.video_file.file_size,
                    'file_path': video.video_file.file_path
                }
            
            return video_data
            
        except Exception as e:
            current_app.logger.error(f"获取视频详情异常: {str(e)}")
            return None
    
    @classmethod
    def audit_video(cls, video_id: int, status: int, audit_reason: str = None) -> Dict[str, Any]:
        """
        审核用户视频
        
        Args:
            video_id: 视频ID
            status: 审核状态（2=通过，3=拒绝）
            audit_reason: 审核原因
            
        Returns:
            审核结果
        """
        try:
            if status not in [cls.STATUS_APPROVED, cls.STATUS_REJECTED]:
                return {'success': False, 'error': '无效的审核状态'}
            
            video = UserVideo.query.get(video_id)
            if not video:
                return {'success': False, 'error': '视频不存在'}
            
            if video.status != cls.STATUS_PENDING:
                return {'success': False, 'error': '该视频已审核，不能重复审核'}
            
            # 更新审核状态
            video.status = status
            video.audit_reason = audit_reason
            
            db.session.commit()
            
            status_text = '审核通过' if status == cls.STATUS_APPROVED else '审核拒绝'
            
            return {
                'success': True,
                'data': video.to_dict(),
                'message': f'视频{status_text}'
            }
            
        except Exception as e:
            db.session.rollback()
            current_app.logger.error(f"审核视频异常: {str(e)}")
            return {'success': False, 'error': f'审核失败: {str(e)}'}
    
    @classmethod
    def get_pending_videos(cls, page: int = 1, per_page: int = 20) -> Dict[str, Any]:
        """
        获取待审核视频列表（管理员用）
        
        Args:
            page: 页码
            per_page: 每页数量
            
        Returns:
            分页的待审核视频列表
        """
        try:
            pagination = UserVideo.query.filter_by(status=cls.STATUS_PENDING)\
                .order_by(UserVideo.created_at.asc())\
                .paginate(page=page, per_page=per_page, error_out=False)
            
            videos = []
            for video in pagination.items:
                video_data = video.to_dict()
                # 添加用户信息
                if video.user:
                    video_data['user_info'] = {
                        'id': video.user.id,
                        'nickname': video.user.nickname,
                        'phone': video.user.phone
                    }
                videos.append(video_data)
            
            return {
                'videos': videos,
                'pagination': {
                    'page': pagination.page,
                    'pages': pagination.pages,
                    'per_page': pagination.per_page,
                    'total': pagination.total,
                    'has_next': pagination.has_next,
                    'has_prev': pagination.has_prev
                }
            }
            
        except Exception as e:
            current_app.logger.error(f"获取待审核视频异常: {str(e)}")
            return {'videos': [], 'pagination': {}}
    
    @classmethod
    def get_user_video_stats(cls, user_id: int) -> Dict[str, Any]:
        """
        获取用户视频统计信息
        
        Args:
            user_id: 用户ID
            
        Returns:
            统计信息
        """
        try:
            total = UserVideo.query.filter_by(user_id=user_id).count()
            pending = UserVideo.query.filter_by(user_id=user_id, status=cls.STATUS_PENDING).count()
            approved = UserVideo.query.filter_by(user_id=user_id, status=cls.STATUS_APPROVED).count()
            rejected = UserVideo.query.filter_by(user_id=user_id, status=cls.STATUS_REJECTED).count()
            
            return {
                'total': total,
                'pending': pending,
                'approved': approved,
                'rejected': rejected,
                'remaining_slots': max(0, cls.MAX_VIDEOS_PER_USER - total),
                'can_upload': total < cls.MAX_VIDEOS_PER_USER
            }
            
        except Exception as e:
            current_app.logger.error(f"获取用户视频统计异常: {str(e)}")
            return {
                'total': 0, 'pending': 0, 'approved': 0, 'rejected': 0,
                'remaining_slots': cls.MAX_VIDEOS_PER_USER, 'can_upload': True
            }
    
    @classmethod
    def _validate_video_file(cls, file_data: Dict[str, Any]) -> Dict[str, Any]:
        """验证视频文件"""
        try:
            # 检查文件大小
            file_size = file_data.get('file_size', 0)
            if file_size > cls.MAX_FILE_SIZE:
                return {
                    'is_valid': False,
                    'error': f'文件大小超过限制({cls.MAX_FILE_SIZE / 1024 / 1024}MB)'
                }
            
            # 检查文件扩展名
            original_name = file_data.get('original_name', '')
            if '.' in original_name:
                ext = original_name.rsplit('.', 1)[1].lower()
                if ext not in cls.ALLOWED_EXTENSIONS:
                    return {
                        'is_valid': False,
                        'error': f'不支持的文件格式，支持格式: {", ".join(cls.ALLOWED_EXTENSIONS)}'
                    }
            else:
                return {'is_valid': False, 'error': '无效的文件名'}
            
            # 检查视频时长
            duration = file_data.get('duration', 0)
            if duration > cls.MAX_DURATION:
                return {
                    'is_valid': False,
                    'error': f'视频时长超过限制({cls.MAX_DURATION}秒)'
                }
            
            # 检查必需字段
            required_fields = ['video_url', 'original_name']
            for field in required_fields:
                if not file_data.get(field):
                    return {'is_valid': False, 'error': f'缺少必需字段: {field}'}
            
            return {'is_valid': True, 'error': None}
            
        except Exception as e:
            return {'is_valid': False, 'error': f'文件验证失败: {str(e)}'} 